package com.ngkj.zmfptback.business.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import com.ngkj.zmfptCommon.common.bean.CommonReslut;
import com.ngkj.zmfptCommon.common.sftp.SFTPChannel;
import com.ngkj.zmfptCommon.common.sftp.SFTPConstants;
import com.ngkj.zmfptCommon.common.util.ResultEnum;
import com.ngkj.zmfptback.sys.initData.servicie.read.AreaService;
import com.ngkj.zmfptback.business.bean.CommunityEntity;
import com.ngkj.zmfptback.business.bean.Image;
import com.ngkj.zmfptback.business.service.read.CommunityReadService;
import com.ngkj.zmfptback.business.service.read.ImageReadService;
import com.ngkj.zmfptback.business.service.write.CommunityWriteService;
import com.ngkj.zmfptback.business.service.write.ImageWriteService;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author ChenHN
 * @since 2021/12/29 creation
 **/
@RestController
public class CommunityController {

    @Resource
    private CommunityReadService communityReadService;

    @Resource
    private CommunityWriteService communityWriteService;

    @Resource
    private AreaService areaService;

    @Resource
    private ImageWriteService imageWriteService;

    @Resource
    private ImageReadService imageReadService;

    @Resource
    private SFTPChannel sftpChannel;

    @GetMapping("/community/getCommunityPage")
    public CommonReslut getCommunityPage(CommunityEntity communityEntity, int pageNo, int pageSize) {
        try {
            Page<CommunityEntity> page = new Page<>(pageNo, pageSize);
            IPage<CommunityEntity> communityEntityIPage = communityReadService.getCommunityPage(page, communityEntity);
            return new CommonReslut(ResultEnum.ok, communityEntityIPage);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }

    /**
     * 新增小区信息 、图片
     * @param communityEntity
     * @param addFileList
     * @return
     */
    @PostMapping("/community/addCommunity")
    public CommonReslut addCommunity(CommunityEntity communityEntity, MultipartFile[] addFileList) throws Exception {
        try {
            String areaCode = communityEntity.getAreaCode();
            String qywzid = communityEntity.getQywzid();
            String[] splits = qywzid.split(";");
            Long id = areaService.getAreaIdByAreaCode(areaCode);
            if (!id.toString().equals(splits[splits.length - 1])) {
                communityEntity.setSqlsh(null);
            }
            splits[splits.length - 1] = id.toString();
            Stream<String> splits1 = Stream.of(splits);
            String qywzids = splits1.collect(Collectors.joining(";"));
            communityEntity.setQywzid(qywzids);
            communityEntity.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            communityWriteService.addCommunity(communityEntity);
            Map<String, String> map = SFTPConstants.getConnectParameter();
            ChannelSftp channel = sftpChannel.getChannel(map, 60000);
            StringBuilder dir = new StringBuilder("/usr/local/static/images/business");
            String time = new SimpleDateFormat("yyyyMMdd").format(new Date());
            dir.append("/" + time);

            SftpATTRS attrs = null;
            try {
                attrs = channel.stat(dir.toString());
            } catch (Exception e) {
                // TODO: handle exception
            }
            if (attrs == null) {
                channel.mkdir(dir.toString());
            }
            for (MultipartFile multipartFile : addFileList) {
                String originalFilename = multipartFile.getOriginalFilename();
                String file = dir.toString() + "/" + UUID.randomUUID().toString().replace("-", "") + "_" + originalFilename;
                channel.put(multipartFile.getInputStream(), file, ChannelSftp.OVERWRITE);
                Image image = new Image();
                image.setType("01");
                image.setName(originalFilename);
                String[] split = file.split("/static");
                image.setPath(split[1]);
                image.setTypeId(communityEntity.getXqlsh());
                imageWriteService.addImage(image);
            }
            sftpChannel.closeChannel();
            return new CommonReslut(ResultEnum.ok);
        } catch (Exception e) {
            sftpChannel.closeChannel();
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }

    /**
     * 修改小区信息 、图片
     * @param communityEntity
     * @param deleteId
     * @param addFileList
     * @return
     */
    @PostMapping("/community/editCommunity")
    public CommonReslut editCommunity(CommunityEntity communityEntity,String deleteId,MultipartFile[] addFileList ) throws Exception {
        try {
            //修改基础信息
            String areaCode = communityEntity.getAreaCode();
            if (!StringUtils.isEmpty(areaCode)) {
                String qywzid = communityEntity.getQywzid();
                String[] splits = qywzid.split(";");
                Long id = areaService.getAreaIdByAreaCode(areaCode);
                if (!id.toString().equals(splits[splits.length - 1])) {
                    communityEntity.setSqlsh(null);
                }
                splits[splits.length - 1] = id.toString();
                Stream<String> splits1 = Stream.of(splits);
                String qywzids = splits1.collect(Collectors.joining(";"));
                communityEntity.setQywzid(qywzids);
            }
            communityWriteService.editCommunity(communityEntity);
            //增加图片 且 删除图片
            if ((!ObjectUtils.isEmpty(addFileList) && addFileList.length > 0) || (!StringUtils.isEmpty(deleteId))) {
                Map<String, String> map = SFTPConstants.getConnectParameter();
                ChannelSftp channel = sftpChannel.getChannel(map, 60000);
                if (!ObjectUtils.isEmpty(addFileList) && addFileList.length > 0) {
                    StringBuilder dir = new StringBuilder("/usr/local/static/images/business");
                    String time = new SimpleDateFormat("yyyyMMdd").format(new Date());
                    dir.append("/" + time);
                    SftpATTRS attrs = null;
                    try {
                        attrs = channel.stat(dir.toString());
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    if (attrs == null) {
                        channel.mkdir(dir.toString());
                    }
                    for (MultipartFile multipartFile : addFileList) {
                        String originalFilename = multipartFile.getOriginalFilename();
                        String file = dir.toString() + "/" + UUID.randomUUID().toString().replace("-", "") + "_" + originalFilename;
                        System.out.println(file);
                        channel.put(multipartFile.getInputStream(), file, ChannelSftp.OVERWRITE);
                        Image image = new Image();
                        image.setType("01");
                        image.setName(originalFilename);
                        String[] split = file.split("/static");
                        image.setPath(split[1]);
                        image.setTypeId(communityEntity.getXqlsh());
                        imageWriteService.addImage(image);
                    }
                }
                else {
                    String[] ids = deleteId.split(";");
                    List<String> list = Arrays.asList(ids);
                    List<Image> deleteFileList =  imageReadService.getImageListByIds(list);
                    for (Image image : deleteFileList) {
                        Long id = image.getId();
                        String path = image.getPath();
                        String filePath = "/usr/local/static" + path;
                        imageWriteService.deleteImage(id);
                        SftpATTRS attrs = null;
                        try {
                            attrs = channel.stat(filePath);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                        if (attrs != null) {
                            channel.rm(filePath);
                        }
                    }
                }
            }
            sftpChannel.closeChannel();
            return new CommonReslut(ResultEnum.ok);
        } catch (Exception e) {
            e.printStackTrace();
            sftpChannel.closeChannel();
            return new CommonReslut(ResultEnum.error);
        }
    }


    @DeleteMapping("/community/deleteCommunity")
    public CommonReslut deleteCommunity(Long xqlsh) {
        try {
            communityWriteService.deleteCommunity(xqlsh);
            List<Image> imageList = imageReadService.getImageListByTypeId(xqlsh);
            if (imageList.size()>0){
                Map<String, String> map = SFTPConstants.getConnectParameter();
                ChannelSftp channel = sftpChannel.getChannel(map, 60000);
                for (Image image : imageList) {
                    String filePath = "/usr/local/static"+image.getPath();
                    SftpATTRS attrs = null;
                    try {
                        attrs = channel.stat(filePath);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                    if (attrs != null) {
                        channel.rm(filePath);
                    }
                }
                imageWriteService.deleteImageByTypeId(xqlsh,"01");
            }
            return new CommonReslut(ResultEnum.ok);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }


    @GetMapping("getCommunity")
    public CommonReslut getCommunity(String qywzid,String sqid){
        try {
            List<CommunityEntity> communityEntities = communityReadService.getCommunity(qywzid,sqid);
            return new CommonReslut(ResultEnum.ok,communityEntities);
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonReslut(ResultEnum.error);
        }
    }

}
